import { useEffect, useState } from 'react';
import '../index.less';
import { Button, Form, Input, InputNumber, message, Modal, Popconfirm, Select, Space, Table } from 'antd';
import {
  getWhiteList, saveWhiteList, queryEquipmentList
} from '../services'
import { useRequest } from 'ahooks';
import { PAGINATION_CONFIG, REG_EXP } from '@/constants';
import { Access } from '@umijs/max';

export interface WhiteListModalProps {
  open: boolean
  onCancel?: (refresh?: boolean) => void
  id?: number
  title?: string
}

const statusTextMap = ['', '启用', '禁用', '已删除']

const StubEditPage: React.FC<WhiteListModalProps> = (props) => {
  const [editForm] = Form.useForm()
  const [params, setParams] = useState<any>({pageNum: 1, pageSize: 10})
  const { data, loading, refresh } = useRequest(() => getWhiteList(params), {
    ready: !!params.id,
    refreshDeps: [params],
  })
  const saveReq = useRequest(saveWhiteList, {manual: true})
  const equipmentList = useRequest(queryEquipmentList, {manual: true})
  const onCancel = (refresh?: boolean) => {
    editForm.resetFields()
    props.onCancel?.(refresh)
  }

  const add = () => {
    const params: any = {
      stationId: props.id,
    }
    Modal.confirm({
      title: '添加白名单',
      content: <Form layout='vertical'>
        <Form.Item label='手机号'>
          <Input placeholder='请输入' onChange={({target}) => params.phone = target.value} />
        </Form.Item>
        <Form.Item label='设备'>
          <Select
            placeholder='请选择'
            options={equipmentList.data?.data.map(item => ({label: item.name, value: item.id}))}
            onChange={value => params.equipmentId = value}
          />
        </Form.Item>
        <Form.Item label='每月限制度数'>
          <InputNumber
            placeholder='请输入'
            onChange={value => params.limitPower = value}
            style={{width: '100%'}}
            min={0}
            precision={2}
            addonAfter='度'
          />
        </Form.Item>
      </Form>,
      onOk: async () => {
        if (!params.phone || !REG_EXP.PHONE.test(params.phone)) {
          message.error('请输入正确的手机号')
          return Promise.reject()
        }
        if (!params.equipmentId) {
          message.error('请选择设备')
          return Promise.reject()
        }
        if (!params.limitPower && params.limitPower !== 0) {
          message.error('请输入每月限制度数')
          return Promise.reject()
        }
        params.state = 1;
        return saveWhiteList(params).then(refresh)
      }
    })
  }
  const edit = (record) => {
    const params: any = {
      stationId: props.id,
      phone: record.phone,
      equipmentId:record.equipmentId,
      limitPower:record.limitPower
    }
    Modal.confirm({
      title: '编辑白名单',
      content: <Form  layout='vertical'>
        <Form.Item label='手机号'>
          <Input placeholder='请输入' disabled={true} value={record.phone} />
        </Form.Item>
        <Form.Item label='设备'>
          <Select
            placeholder='请选择'
            value={record.equipmentId}
          />
        </Form.Item>
        <Form.Item label='每月限制度数'>
          <InputNumber
            value={record.limitPower}
            placeholder='请输入'
            onChange={value => params.limitPower = value}
            style={{width: '100%'}}
            min={0}
            precision={2}
            addonAfter='度'
          />
        </Form.Item>
      </Form>,
      onOk: async () => {

        if (!params.limitPower && params.limitPower !== 0) {
          message.error('请输入每月限制度数')
          return Promise.reject()
        }
        params.state = 1;
        return saveWhiteList(params).then(refresh)
      }
    })
  }
  const del = (record: any) => {
    return saveReq.runAsync({id: record.id, state: 3, equipmentId: record.equipmentId, phone: record.phone}).then(refresh)
  }
  const disable = (record: any) => {
    return saveReq.runAsync({id: record.id, state: 2}).then(refresh)
  }
  const enable = (record: any) => {
    return saveReq.runAsync({id: record.id, state: 1}).then(refresh)
  }

  useEffect(() => {
    if (props.open) {
      setParams({id: props.id, pageNum: 1, pageSize: 10})
      equipmentList.run({pageNum: 1, pageSize: 10, stationTitle: props.title})
    }
    else {
      setParams({pageNum: 1, pageSize: 10})
    }
  }, [props.open])
  
  return (
    <Modal
      title='白名单'
      className='container'
      open={props.open}
      onCancel={() => onCancel()}
      width={880}
      footer={[<Button key='cancelBtn' onClick={() => onCancel()}>关闭</Button>]}
    >
      <Button type='primary' onClick={add} style={{marginBottom: 12}}>添加白名单</Button>
      <Table
        rowKey={'id'}
        loading={loading}
        dataSource={data?.data || []}
        columns={[
          {title: '白名单手机号', dataIndex: 'phone'},
          {title: '每月最大共享度数(度)', dataIndex: 'limitPower'},
          {title: '本月已充度数(度)', dataIndex: 'chargePower'},
          {title: '本月剩余度数(度)', dataIndex: 'lastPower'},
          {title: '当前月份', dataIndex: 'month'},
          {title: '操作', key: 'operations', render: (val, record) => {
            return <Space>
              <a onClick={() => edit(record)}>编辑</a>

              <Access accessible={true}>
                <Popconfirm title='确认删除吗?' onConfirm={() => del(record)}>
                  <a>删除</a>
                </Popconfirm>
              </Access>
            </Space>
          }}
        ]}
         pagination={{
          ...PAGINATION_CONFIG,
          current: params.pageNum,
          pageSize: params.pageSize,
          total: data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setParams({
              ...params,
              pageNum: page === params.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
    </Modal>
  );
};

export default StubEditPage;
